package com.jkl.webserver.Tool;

import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.Comparator;

//该类用于创建文件和目录,和删除某个目录
@Component
public class FileCreator {
    public FileCreator(){}
    public void createFile(File file){
        try {
            if (file.createNewFile()) {
                System.out.println(file.toPath()+"文件创建成功");
            } else {
                System.out.println(file.toPath()+"文件已存在！");
            }
        } catch (IOException e) {
            System.out.println(file.toPath()+"创建文件时出现错误！");
            e.printStackTrace();
        }
    }
    public void createFile(String ParentPath,String fileName,String fileType){
        File file = new File(ParentPath,fileName+"."+fileType);
        createFile(file);
    }
    public void createFile(File ParentFile,String fileName,String fileType){
        File file = new File(ParentFile,fileName+"."+fileType);
        createFile(file);
    }
    public void createDir(File file){
        if (file.mkdir()) {
            System.out.println(file.toPath()+"目录创建成功");
        } else {
            System.out.println(file.toPath()+"目录创建失败!");
        }
    }
    public void createDir(String ParentPath,String DirName){
        File file = new File(ParentPath,DirName);
        createDir(file);
    }
    public void createDir(File ParentFile,String DirName){
        File file = new File(ParentFile,DirName);
        createDir(file);
    }
    public void deleteDir(File dir){
        try {
            Files.walk(dir.toPath())
                    .sorted(Comparator.reverseOrder())  // 逆序删除，先删除子文件/目录
                    .forEach(path -> {
                        try
                        {
                            Files.delete(path);
//                            System.out.println("Deleted: " + path);
                        } catch (IOException e) {
                            System.err.println("Error deleting: " + path + " - " + e.getMessage());
                        }
                    });
//            System.out.println("Directory deleted successfully.");
        } catch (IOException e) {
            System.err.println("Error deleting directory: " + e.getMessage());
        }
    }
    public void deleteDir(String dirPath){
        deleteDir(new File(dirPath));
    }
}